<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .slider-bar {
            position: absolute;
            left: 50%;
            top: 300px;
            margin-left: 600px;
            width: 45px;
            height: 130px;
            background-color: pink;
        }
        
        .w {
            width: 1200px;
            margin: 10px auto;
        }
        
        .header {
            height: 150px;
            background-color: purple;
        }
        
        .banner {
            height: 250px;
            background-color: skyblue;
        }
        
        .main {
            height: 1000px;
            background-color: yellowgreen;
        }
        
        span {
            display: none;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主体部分</div>
 <script>
     var slider_bar = document.querySelector('.slider-bar')
     var goback = document.querySelector('.goBack')
     var main = document.querySelector('.main')
     var banner = document.querySelector('.banner')
       var  banner_top =    banner.offsetTop
       var slider_top = slider_bar.offsetTop
       var main_top = main.offsetTop
       var slider_fix = slider_top - banner_top
       document.addEventListener('scroll',function(){
           if(window.pageYOffset >= banner_top){
               slider_bar.style.position = 'fixed'
               slider_bar.style.top = slider_fix + 'px'
           }else{
            slider_bar.style.position = 'absolute'
               slider_bar.style.top = 300 + 'px'
           }
           if(window.pageYOffset>=main_top){
               goback.style.display = 'block'
           }else {
            goback.style.display = 'none'
           }
       })
       goback.addEventListener('click',function(){
           animates(window,0)
       })
       function animates(obj, target,callback) {
            clearInterval(obj.tame)
            obj.tame= setInterval(function () {
                var step = (target - obj.pageYOffset) / 10
                step = step > 0 ? Math.ceil(step) : Math.floor(step)
                if (obj.pageYOffset == target) {
                    clearInterval(obj.tame)
                    callback && callback()
                }
                // obj.style.left = obj.offsetLeft + step + 'px'
                window.scroll(0,window.pageYOffset + step )
            }, 15)
        }
 </script>
</body>


</html>